{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "697706a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''\n",
    "os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d0ec1fef",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import LlamaConfig, LlamaForCausalLM, AutoTokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "92d39620",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LlamaConfig {\n",
       "  \"_name_or_path\": \"fpf-13b-32k/checkpoint-7650\",\n",
       "  \"architectures\": [\n",
       "    \"LlamaForCausalLM\"\n",
       "  ],\n",
       "  \"attention_bias\": false,\n",
       "  \"bos_token_id\": 1,\n",
       "  \"eos_token_id\": 2,\n",
       "  \"hidden_act\": \"silu\",\n",
       "  \"hidden_size\": 5120,\n",
       "  \"initializer_range\": 0.02,\n",
       "  \"intermediate_size\": 13824,\n",
       "  \"max_position_embeddings\": 32768,\n",
       "  \"model_type\": \"llama\",\n",
       "  \"num_attention_heads\": 40,\n",
       "  \"num_hidden_layers\": 9,\n",
       "  \"num_key_value_heads\": 40,\n",
       "  \"pad_token_id\": 0,\n",
       "  \"pretraining_tp\": 1,\n",
       "  \"rms_norm_eps\": 1e-05,\n",
       "  \"rope_scaling\": null,\n",
       "  \"rope_theta\": 10000.0,\n",
       "  \"tie_word_embeddings\": false,\n",
       "  \"torch_dtype\": \"float16\",\n",
       "  \"transformers_version\": \"4.35.2\",\n",
       "  \"use_cache\": true,\n",
       "  \"vocab_size\": 32000\n",
       "}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "half_config = LlamaConfig.from_pretrained('mesolitica/llama-13b-hf-32768-fpf', \n",
    "                                             num_hidden_layers = 9)\n",
    "half_config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "95245a04",
   "metadata": {},
   "outputs": [],
   "source": [
    "small = LlamaForCausalLM(half_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "6294aaa0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "3194456ec1fa46abb2506d82e5088285",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading checkpoint shards:   0%|          | 0/3 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "model = LlamaForCausalLM.from_pretrained('mesolitica/llama-13b-hf-32768-fpf')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a744d1f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.nn as nn\n",
    "\n",
    "def copy_layers(src_layers, dest_layers, layers_to_copy):\n",
    "    layers_to_copy = nn.ModuleList([src_layers[i] for i in layers_to_copy])\n",
    "    assert len(dest_layers) == len(layers_to_copy), f\"{len(dest_layers)} != {len(layers_to_copy)}\"\n",
    "    dest_layers.load_state_dict(layers_to_copy.state_dict())\n",
    "\n",
    "layers_to_copy = [0,1,2,3,4,5,6,7,8]\n",
    "\n",
    "copy_layers(model.model.layers, small.model.layers, layers_to_copy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a48eda38",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.model.embed_tokens.load_state_dict(model.model.embed_tokens.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "67297125",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.model.norm.load_state_dict(model.model.norm.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "95fe01ba",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.lm_head.load_state_dict(model.lm_head.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "60c688b5",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3182525440"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum(p.numel() for p in small.parameters())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "b4be57f4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.bfloat16"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "torch.bfloat16"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "647e12c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "small = small.type(torch.bfloat16)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "bc0c3658",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e98e3841bbeb41a5a88372a178ac1dab",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "tokenizer_config.json:   0%|          | 0.00/725 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0889d0d00d7a4958a850d335b7637c99",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "tokenizer.model:   0%|          | 0.00/500k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6b1a55d903db4fd288358b63bcc7c702",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "tokenizer.json:   0%|          | 0.00/1.84M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "2d1b26d734c44aca8e3bae55b46ecb04",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "special_tokens_map.json:   0%|          | 0.00/414 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained('mesolitica/llama-13b-hf-32768-fpf')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "c68de176",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/ubuntu/.local/lib/python3.10/site-packages/transformers/utils/hub.py:703: UserWarning: The `organization` argument is deprecated and will be removed in v5 of Transformers. Set your organization directly in the `repo_id` passed instead (`repo_id={organization}/{model_id}`).\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b902135fe5e544699592f576663a550c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "tokenizer.model:   0%|          | 0.00/500k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "CommitInfo(commit_url='https://huggingface.co/huseinzol05/llama-3.2b-hf-32768/commit/de660ceaad3cc6f9613156ca57bae6edc5461384', commit_message='Upload tokenizer', commit_description='', oid='de660ceaad3cc6f9613156ca57bae6edc5461384', pr_url=None, pr_revision=None, pr_num=None)"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer.push_to_hub('llama-3.2b-hf-32768', organization='huseinzol05')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "b99b2bc5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4e0a5bc5b7e143429027fe64c4d48fdc",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "model-00001-of-00002.safetensors:   0%|          | 0.00/4.98G [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f434b8cf43dd45f6a2cfaf628d5e44e9",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "model-00002-of-00002.safetensors:   0%|          | 0.00/1.39G [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "40d072dc8a07474296336715720b68cf",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Upload 2 LFS files:   0%|          | 0/2 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "CommitInfo(commit_url='https://huggingface.co/huseinzol05/llama-3.2b-hf-32768/commit/71e759804927662962bd14fe3fe40dee1fdeb99e', commit_message='Upload LlamaForCausalLM', commit_description='', oid='71e759804927662962bd14fe3fe40dee1fdeb99e', pr_url=None, pr_revision=None, pr_num=None)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.push_to_hub('llama-3.2b-hf-32768', organization='huseinzol05', safe_serialization=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "843049fc",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
